package cn.zyjblogs.netty.codec2;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 说明
 * 1、自定义一个Handler 需要继承netty规定好的某个HandlerAdapter
 */
public class NIOServerHandler extends SimpleChannelInboundHandler<DataInfo.MyMessage> {


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, DataInfo.MyMessage msg) throws Exception {
        DataInfo.MyMessage.DataType dataType = msg.getDataType();
        if (dataType == DataInfo.MyMessage.DataType.StudentType){
            DataInfo.Student student = msg.getStudent();
            System.out.println("学生id="+student.getId()+" name="+student.getName());
            return;
        }
        if (dataType == DataInfo.MyMessage.DataType.WorkerType){
            DataInfo.Worker student = msg.getWorker();
            System.out.println("worker age="+student.getAge()+" name="+student.getName());
            return;
        }
        System.out.println("传输类型不正确");
    }

    //数据读取完毕
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        // super.channelReadComplete(ctx);
        //writeAndFlush  是write和flush 方法  将数据写入到缓存 并刷新
        //一般将，我们需要对发送数据进行编码
        ctx.writeAndFlush(Unpooled.copiedBuffer("hello,客户端~o( =∩ω∩= )m喵 || 1", CharsetUtil.UTF_8));
    }

    //处理异常 一般是需要关闭通道
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        // super.exceptionCaught(ctx, cause);
        ctx.close();
    }
}
